<?php

namespace app\api\controller;


use app\common\model\ActiveJoin;
use app\common\model\MallConfig;
use app\service\MsgService;

class Active extends Base
{

    public $activeModel;

    public function __construct()
    {
        parent::__construct();
        $this->activeModel = new \app\common\model\Active();
    }

    /**
     * 活动列表
     * @return \think\response\Json
     */
    public function active_list()
    {
        $time = time();
        $where = "(js_type=1 and is_start=1) or (js_type=2 and start>={$time} and end<={$time})";
        $list = $this->activeModel->where($where)->order('id desc')->select();
        $new = [
            [], []
        ];
        foreach ($list as $key => $value) {
            if ($value['type'] == '展示类') {
                $new[0][] = $value;
            } else {
                $new[1][] = $value;

            }
        }
        return returnJson(200, '', $new);

    }

    /**
     * 详情
     * @return \think\response\Json
     */
    public function detail()
    {
        $data = input('');
        $active = [];
        if ($data['id']) {
            $active = \app\common\model\Active::getOne(['id' => $data['id']]);
            $active['num'] = ActiveJoin::getCount(['aid' => $data['id']]);
            $list_uid = ActiveJoin::getColumn(['aid' => $data['id']], 'uid');
            if ($list_uid) {
                $active['list'] = \app\common\model\User::getPage(['id' => ['in', $list_uid]], 1, 3, '', 'headimgurl');
            } else {
                $active['list'] = [];
            }
            $res = $this->is_join($active);
            $active['message'] = $res['message'];
            $active['code'] = $res['code'];
        }
        return returnJson(200, '', $active);
    }

    /**
     * 参与活动列表
     * @return \think\response\Json
     */
    public function join_list()
    {
        $where = array();
        $where['aid'] = input('aid');
        $where['is_pingfen'] = 1;
        $page = max(input('page'), 1);
        $size = 20;
        $list = \app\common\model\ActiveJoin::getPage($where, $page, $size, 'score desc,id desc');
        $is_join = ActiveJoin::getOne(['aid' => $where['aid'], 'uid' => $this->uid]) ? true : false;
        if (!$list) {
            $list = [];
            return returnJson(200, '', compact('list', 'is_join'));
        }
        $active = \app\common\model\Active::getColumn([], 'id,title');
        foreach ($list as $k => $v) {
            $list[$k]['title'] = isset($active[$v['aid']]) ? $active[$v['aid']] : '';
            $user_info = \app\common\model\User::getOne(['id' => $v['uid']], 'nickname,headimgurl');
            $list[$k]['nickname'] = $user_info['nickname'];
            $list[$k]['headimgurl'] = $user_info['headimgurl'];
            $list[$k]['time_preg'] = time_preg(strtotime($v['create_time']));

        }
        return returnJson(200, '', compact('list', 'is_join'));
    }

    /**
     * 参与活动
     * @return \think\response\Json
     */
    public function join()
    {
        $data = input('');
        if ($data['aid']) {
            $active = \app\common\model\Active::getOne(['id' => $data['aid']]);
            if ($active) {
                if (($active['js_type'] == 1 && $active['is_start'] == 1) || ($active['js_type'] == 2 && $active['start'] <= time() && $active['end'] >= time())) {
                    $msg = $this->is_join($active);
                    if ($msg['code'] == 202) {
                        return returnJson(202, $msg['message']);
                    }
                    $save_data = [
                        'uid' => $this->uid,
                        'update_time' => time(),
                        'create_time' => time(),
                        'source' => $data['source'],
                        'aid' => $data['aid'],
                        'time' => date('Y-m-d'),
                        'sid' => $this->sid
                    ];
                    $res = ActiveJoin::create($save_data);
                    if ($res) {
                        //通知管理员
                        $active_manager = explode(',', config('active_manager'));
                        if ($active_manager) {
                            $userInfo = \app\common\model\User::getAll(['id' => ['in', $active_manager]]);
                            if ($userInfo) {
                                foreach ($userInfo as $val) {
                                    $first = "有新的用户参与到活动中来了";
                                    MsgService::S(['mall_id' => $val['mall_id']])->sendTemp('ACTIVE', $val['mall_id'], $val['id'], [
                                        'first' => $first,
                                        'keyword1' => $this->member['nickname'] . '(ID:' . $this->uid . ')',
                                        'keyword2' => $active['title'] . '(ID:' . $active['id'] . ')',
                                        'keyword3' => date('Y-m-d H:i:s'),
                                        'remark' => "有用户参与了活动，可前往管理后台查看"
                                    ]);
                                }
                            }
                        }


                        return returnJson(200, $msg['message']);
                    }

                }
                return returnJson(202, '活动未开始或者已结束');
            }
        }
        return returnJson(202, ' 活动不存在');
    }

    /**
     * 当前用户是否可参与此次活动
     * @param $active
     * @return \think\response\Json
     */
    private function is_join($active)
    {
        $date = date('Y-m-d');
        switch ($active['join_cycle']) {
            case 1: //按天计算
                if ($this->sid) {
                    $active_join = ActiveJoin::getOne(['aid' => $active['id'], 'sid' => $this->sid, 'time' => $date]);
                } else {
                    $active_join = ActiveJoin::getOne(['aid' => $active['id'], 'uid' => $this->uid, 'time' => $date]);
                }
                if ($active_join) {
                    return [
                        'code' => 202,
                        'message' => '您今天已经参与过了，明天再来吧',
                    ];
                } else {
                    return [
                        'code' => 200,
                        'message' => '参与成功，记得明天再来喔',
                    ];
                }
                break;
            case 2:  // 按周计算
                $week = date('w', time());
                $week = $week == 0 ? 7 : $week;
                $start = strtotime(date('Y-m-d' . ' 23:59:59', strtotime('-' . $week . ' days')));
                $end = strtotime(date('Y-m-d' . ' 24:00:00', strtotime('+' . 7 - $week . ' days')));
                if ($this->sid) {
                    $active_join = ActiveJoin::getOne(['aid' => $active['id'], 'sid' => $this->sid, 'create_time' => ['between', [$start, $end]]]);
                } else {
                    $active_join = ActiveJoin::getOne(['aid' => $active['id'], 'uid' => $this->uid, 'create_time' => ['between', [$start, $end]]]);
                }
                if ($active_join) {
                    return [
                        'code' => 202,
                        'message' => '您本周已经参与过了，下周再来吧',
                    ];
                } else {
                    return [
                        'code' => 200,
                        'message' => '参与成功，记得下周再来喔',
                    ];
                }
                break;
            case 3: //按活动计算
                if ($this->sid) {
                    $active_join = ActiveJoin::getOne(['aid' => $active['id'], 'sid' => $this->sid]);
                } else {
                    $active_join = ActiveJoin::getOne(['aid' => $active['id'], 'uid' => $this->uid]);
                }
                if ($active_join) {
                    return [
                        'code' => 202,
                        'message' => '本次活动已经参与过了，您可以尝试参与一下其他的活动',
                    ];
                } else {
                    return [
                        'code' => 200,
                        'message' => '参与成功',
                    ];
                }
                break;
        }
    }

}

